package com.server.handler;

import com.entity.AppInfo;
import com.entity.MsgData;
import com.entity.MsgType;
import groovy.util.logging.Slf4j;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLongArray;

@Component
@ChannelHandler.Sharable
public class TcpHandler extends SimpleChannelInboundHandler<MsgData> {

    public volatile CopyOnWriteArrayList<ChannelHandlerContext> INVALID_CONNECTION = new CopyOnWriteArrayList<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MsgData msg) throws Exception {

        System.out.println("服务端收到消息：" + msg.getType());
        switch (msg.getType()) {
            case INIT:
                init(msg.getAppInfo());
                break;
            case PING:
                ping(msg.getAppInfo());
                break;
            default:
        }
    }

    private void ping(AppInfo appInfo) {

    }

    private void init(AppInfo appInfo) {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        INVALID_CONNECTION.add(ctx);
        System.out.println("客户端连接成功: client address :" + ctx.channel().remoteAddress());
        System.out.println("当前共有个客户端连接:" + INVALID_CONNECTION.size());
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        INVALID_CONNECTION.remove(ctx);
        System.out.println("客户端连接关闭: client address :" + ctx.channel().remoteAddress());
        System.out.println("当前共有个客户端连接:" + INVALID_CONNECTION.size());
    }


}
